<?
# /home/clients/advsm_ftp0/domains/vkposter.com/html

require_once '/home/clients/advsm_ftp0/domains/vkposter.com/html/classes/Bootstrap.php';

$currentDay = date('Y-m-d', time());
$currentTime = date('H:i:s', time());

$_adapter = Zend_Db_Table_Abstract::getDefaultAdapter();
		
$writer = new Zend_Log_Writer_Db($_adapter, 'log');

$log = new Log($writer);

$select = TurnPostPeer::getInstance()->select();
$select->where('post_date <= ?', $currentDay)
        ->where('post_time <= ?', $currentTime)
        ->where('is_posted = ?', 0);

$posts = TurnPostPeer::getInstance()->fetchAll($select);

if ($posts->count()) {
    foreach($posts as $post){
        $user = $post->getUserRowByUserId();
        $turn = $post->getTurnRowByTurnId();
        $group = $turn->getGroupsRowByGroupId();
        $vk = vk::getInstance();

		$image = $post->image;
		if ($image) {
		    // получаем сервер для сохранения фотографии
		    $data = array(
		        'gid' => $group->vk_id,
		        'access_token' => $user->access_token
		    );

		    $serverPhoto = $vk->api('photos.getWallUploadServer', $data);
		    $log->info('Crone run trunks: vk api request (photos.getWallUploadServer) params (' . $vk->getStrParams() . '); response=' . $vk->getStrResponse());
		    
		    
		    if (strpos($image, 'http://') !== false) {
		        // скачиваем картинку
		        $filePutResult = file_put_contents('/home/clients/advsm_ftp0/domains/vkposter.com/html/images/post/'.$post->post_id.'.jpg', file_get_contents($image));
		        if ($filePutResult == false) {
		            $log->err('Crone run trunks: error download image of ' . $image . ' in /home/clients/advsm_ftp0/domains/vkposter.com/html/images/post/'.$post->post_id.'.jpg');
		            throw new Exception('Crone run trunks: error download image of ' . $image . ' in /home/clients/advsm_ftp0/domains/vkposter.com/html/images/post/'.$post->post_id.'.jpg');
		        }
		        $image = '/images/post/'.$post->post_id.'.jpg';
		    } else {
		        if (strpos($image, '?') !== false) {
		            $image = substr($image, 0, strpos($image, '?'));
		        }            
		    }
		    $image = '/home/clients/advsm_ftp0/domains/vkposter.com/html' . $image;
		    
		    $log->info('Crone run trunks: image path ' . $image);
		    $post_data = array('photo' => '@' . $image);
		    $curl = curl_init();
		    curl_setopt($curl, CURLOPT_URL, $serverPhoto['upload_url']);
		    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		    curl_setopt($curl, CURLOPT_POST, 1);
		    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
		    $response = curl_exec($curl);
		    if ($response === FALSE) {
		        $log->err('Crone run trunks: upload foto ' . curl_error($curl));
		        throw new Exception('Crone run trunks: upload foto ' . curl_error($curl));
		    }
		    curl_close($curl);
		    
		    $log->info('Crone run trunks: response ' . $response . ' upload image ' . $image . ' in ' . $serverPhoto['upload_url']);
		    
		    $response = Zend_Json::decode($response);
		    
		    // формируем данные
		    $data = array(
		        'gid' => $group->vk_id,
		        'server' => $response['server'],
		        'photo' => $response['photo'],
		        'hash' => $response['hash'],
		        'access_token' => $user->access_token
		    );
		    // сохраняем картинку
		    $wallPhoto = $vk->api('photos.saveWallPhoto', $data);
		    $log->info('Crone run trunks: vk api request (photos.saveWallPhoto) params (' . $vk->getStrParams() . '); response=' . $vk->getStrResponse());
		}
		
		if (!isset($wallPhoto[0])) {
			$ph = null;
		} else { 
			$ph = $wallPhoto[0]['id'];
		}

        // постим
        $data = array(
            'owner_id' => '-' . $group->vk_id,
            'attachments' => $ph,
            'message' => $post->text,
            'from_group' => 1,
            'signed' => 0,
            'access_token' => $user->access_token
        );

        $wall = $vk->api('wall.post', $data);

        $log->info('Crone run trunks: vk api request (wall.post) params (' . $vk->getStrParams() . '); response=' . $vk->getStrResponse());

        PostPeer::getInstance()->updatePost(
            new VkUser($user->vk_id),
            $post->post_id,
            $post->text,
            $wallPhoto[0]['id'],
            'http://vk.com/wall-' . $group->vk_id . '_' . $wall['post_id']
        );

        $postRow = TurnPostPeer::getInstance();
        $postRow->update(array('is_posted'=>1), 'id = ' . $post->id);
        $log->info('Crone run trunks: DB update post ' . $post->post_id);
    }
}
